import React from 'react';

class CourseSelect extends React.Component {
    constructor() {
        super();
    }
    state={
        grade:null,
        course:null,
        courses:[],
        _loading:false,
        _status:'保存'
    }

    //渲染年纪下拉框
    renderGradeSelect = () => {
        return (
            <select
                onChange={this.onSelectGrade}
                value={this.state.grade || ''}
            >
                <option value="">请选择年级</option>
                <option value="1">小学</option>
                <option value="2">初中</option>
            </select>
        );
    };
    //选择年纪选项事件
    onSelectGrade = (evt)=>{
        const grade = evt.target.value;
        let courses = null;
        if (grade==1) {
            courses = ["语文","数学"]
        }else{
            courses = ["物理","计算机"]
        }

        this.setState({grade,courses})

        //通知父组件
        this.props.onChange({name:"grade",value:grade})
    }

    handleStateSave=()=>{
        this.setState({
            _loading:true,
            _status:'正则保存中'
        })
        setTimeout(this.setState({
            _loading:false,
            _status:'保存成功'
        }), 5000)

    }

    //渲染课程下拉框
    renderCourseSelect = () => {
        if (this.state._loading) {
            return <img alt="loading" src="/img/loading.gif" />;
        }
        if (!this.state.grade || !this.state.courses.length) return <span />;

        return (
            <select onChange={this.onSelectCourse} value={this.state.course || ''}>
                {[
                    <option value="" key="course-none">
                        选择课程
                    </option>,

                    ...this.state.courses.map((course, i) => (
                        <option value={course} key={i}>
                            {course}
                        </option>
                    ))
                ]}
            </select>
        );
    };

    //选择课程选项事件
    onSelectCourse = (evt)=>{
        const course = evt.target.value;
        this.setState({course})
        //通知父组件
        this.props.onChange({name:"course",value:course})
    }
    render() {
        return(<div>
            {this.renderGradeSelect()}
            <br/>
            {this.renderCourseSelect()}
            <br/>
            <button onClick={this.handleStateSave}>{this.state._status}</button>
        </div>)
    }
}

export default CourseSelect;